package com.whjz.workstation.config.socket.client;
import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
public class EchoClient {

	 public void connect(String addr,int port) throws Exception{
	        EventLoopGroup workGroup=new NioEventLoopGroup();
	        try {
	            Bootstrap b=new Bootstrap();
	            b.group(workGroup)
	             .channel(NioSocketChannel.class)
	             .option(ChannelOption.TCP_NODELAY, true)
	             .handler(new ChannelInitializer<SocketChannel>() {

	                @Override
	                protected void initChannel(SocketChannel sc) throws Exception {
	                    ByteBuf delimiter=Unpooled.copiedBuffer("$_".getBytes());//指定消息分割符
	                    sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
	                    sc.pipeline().addLast(new StringDecoder());
	                    sc.pipeline().addLast(new EchoClientHandler());
	                }
	                 
	            });
	            
	            ChannelFuture f=b.connect(new InetSocketAddress(addr, port)).sync();
	            System.out.println("连接服务器:"+f.channel().remoteAddress()+",本地地址:"+f.channel().localAddress());
	            f.channel().closeFuture().sync();//等待客户端关闭连接
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	        }finally{
	            workGroup.shutdownGracefully();
	        }
	    }
	    
	    public static void main(String[] args) throws Exception{
	        new EchoClient().connect("127.0.0.1", 60000);
	    }
}
